package com.devunion.bogdan.view.project.actions;

import com.devunion.bogdan.model.project.*;
import com.devunion.bogdan.model.project.info.ProjectInfo;
import com.devunion.bogdan.model.project.dao.ProjectDao;
import com.devunion.bogdan.util.IconHelper;
import com.devunion.bogdan.spring.Context;

import javax.swing.*;
import java.awt.event.ActionEvent;

import org.apache.log4j.Logger;

/**
 * @author Viktar Liaskovich
 */
public class ProjectOpenAction extends AbstractAction {
    private static Logger log = Logger.getLogger(ProjectOpenAction.class);
    private ProjectDao projectDao;

    public ProjectOpenAction() {
        super(null, IconHelper.getIcon("OpenProject16.gif"));
        putValue(Action.LARGE_ICON_KEY, IconHelper.getIcon("OpenProject48.gif"));

        projectDao = (ProjectDao) Context.getContext().getBean("projectDao");
    }

    public ProjectOpenAction(String name) {
        super(name);
    }

    public void actionPerformed(ActionEvent evt) {

        ProjectInfo[] infos = projectDao.loadProjectInfos().toArray(new ProjectInfo[0]);

        if (infos.length == 0) {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "There is no projects in database");
            return;
        }

        // TODO: add i18n
        ProjectInfo s = (ProjectInfo) JOptionPane.showInputDialog(
                JOptionPane.getRootFrame(),
                "Projects in database:",
                "Projects",
                JOptionPane.PLAIN_MESSAGE,
                null,
                infos,
                infos[0]);

        if (s != null) {
            try {
                if (ProjectManager.getInstance().getCurrentProject() != null) {
                    ProjectManager.getInstance().closeProject();
                }

                ProjectManager.getInstance().loadProject(s.getProjectId());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
